import os,sys,getopt
from PIL import Image

def resizeThumb(file, compress, crop, dstfilename):
    img = Image.open(file)
    width, height = img.size
    if(crop):
        if width > height:
            delta = (width - height) / 2
            box = (delta, 0, width - delta, height)
            region = img.crop(box)
            width = height
        elif height > width:
            delta = (height - width) / 2
            box = (0, delta, width, height - delta)
            region = img.crop(box)
            height = width
    else:
        region = img
    width = int(width * compress)
    height = int(height * compress)
    region = region.resize((width, height), Image.Resampling.LANCZOS)
    region.save(dstfilename, quality=70)

def makeThumb(file, path, compress, crop):
    filename = os.path.join(path, os.path.basename(file))
    # base, ext = os.path.splitext(os.path.basename(file))
    # filename = os.path.join(path, '%s_thumb%s' % (base,ext))
    resizeThumb(file, compress, crop, filename)

def printHelpInfo():
    print("帮助信息")
    print("{} [-s] [-d] [-c] [--suffix] [--compress]\n快速批量生成缩略图".format(sys.argv[0]))
    print("参数")
    print("-s: 需要转换的图片文件\n\t如果指定为路径，则遍历该路径下所有图片\n\t如果指定为文件，则仅转换该文件")
    print("\t【*】默认路径为：{}".format(os.path.abspath(os.path.dirname(__file__))))
    print("-d: 转换结果保存的目录路径")
    print("\t【*】默认路径为：{}".format(os.path.join(os.path.abspath(os.path.dirname(__file__)), "thumbs")))
    print("-c: 采用裁剪方式，自动裁剪图片中间区域")
    print("--suffix: 仅对指定后缀类型的文件，生成缩略图")
    print("\t【*】默认为：jpg")
    print("--compress：压缩率（0~1之间的小数）")
    print("\t【*】默认为：0.5")
    sys.exit()

def printVersion():
    print(VERSION)
    sys.exit()

def autoCreateDirectory(path):
    if not os.path.exists(path):
        os.makedirs(path)

if __name__ == '__main__':
    VERSION = "1.0.0"
    srcPath = None
    dstPath = None
    suffix = 'jpg'
    crop = False
    compress = 0.5
    opts,args = getopt.getopt(sys.argv[1:], '-s:-d:-h-v-c', ['help','version','suffix=', 'compress='])
    for optName, optValue in opts:
        if(optName in ['-h', '--help']):
            printHelpInfo()
        if(optName in ['-s']):
            srcPath = os.path.join(optValue)
        if(optName in ['-d']):
            dstPath = os.path.join(optValue)
        if(optName in ['-v', '--version']):
            printVersion()
        if(optName in ['--suffix']):
            suffix = optValue
        if(optName in ['-c']):
            crop = True
        if(optName in ['--compress']):
            cp = float(optValue)
            if(cp > 0 and cp < 1):
                compress = cp
    if(srcPath is None):
        srcPath = os.path.abspath(os.path.dirname(__file__))
    if(dstPath is None):
        dstPath = os.path.join(srcPath, 'thumbs')
        autoCreateDirectory(dstPath)
    
    for root, dirs, files in os.walk(srcPath):
        if(root == dstPath):
            break
        for file in files:
            if(file.lower().endswith(suffix)):
                makeThumb(os.path.join(root, file), dstPath, compress, crop)Thumbnail
